package com.bwie.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bwie.mapper.TbUserMapper;
import com.bwie.pojo.TbUser;
import com.bwie.service.TbUserService;
import com.bwie.utils.MobileMessageUtil;
import com.bwie.utils.R;
import com.bwie.vo.LoginInfoVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class TbUserServiceImpl implements TbUserService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    TbUserMapper tbUserMapper;

    @Override
    public R gainCode(String userMobile) {
        String userCode = RandomUtil.randomNumbers(4);
        System.out.println("发送的手机验证码为:" + userCode);
        MobileMessageUtil.sendMobileMessage(userMobile, userCode);

        TbUser tbUser = tbUserMapper.selectOne(new QueryWrapper<TbUser>().lambda().eq(TbUser::getUserMobile, userMobile));
        if (tbUser == null) {
            return R.ERROR(500, "用户不能为空");
        }
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456")
                .claim("userId", tbUser.getUserId())
                .compact();
        String key = "userId :" + tbUser.getUserId();
        stringRedisTemplate.opsForValue().set(key, token, 15, TimeUnit.MINUTES);
        stringRedisTemplate.opsForValue().set(key, userCode);
        return R.OK(userCode);
    }

    @Override
    public R loginMobile(LoginInfoVo loginInfoVo) {
        TbUser tbUser = tbUserMapper.selectOne(new QueryWrapper<TbUser>().lambda().eq(TbUser::getUserMobile, loginInfoVo.getUserMobile()));
        String userCode = stringRedisTemplate.opsForValue().get(loginInfoVo.getUserCode());
        System.out.println(userCode);
        if (loginInfoVo.getUserCode()!= null){
            return R.OK();
        }
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456")
                .claim("userId", tbUser.getUserId())
                .compact();
        String key = "userId :" + tbUser.getUserId();
        stringRedisTemplate.opsForValue().set(key, token, 15, TimeUnit.MINUTES);
        tbUser.setToken(token);
        return R.OK(token);
    }
}
